import { BrowserWindow, app, shell } from 'electron';
import icon from '../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'

let aboutWin = null;

const createaboutWin = () => {
    aboutWin = new BrowserWindow({
        title: 'YangShaoTool about',
        width: 700,
        height: 500,
        autoHideMenuBar: true,
        icon: icon,
        webPreferences: {
            nodeIntegration: true,
            preload: join(__dirname, '../preload/index.js'),
        },
        resizable: false,
        show: false

    });
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
        aboutWin.loadURL(process.env['ELECTRON_RENDERER_URL'])
    } else {
        aboutWin.loadFile(join(__dirname, '../renderer/index.html'))
    }
    // 假设你想在创建窗口后立即打开设置路由
    aboutWin.webContents.on('did-finish-load', () => {
        aboutWin.webContents.send('set-route', '/about');
    });
    aboutWin.webContents.setWindowOpenHandler((details) => {
        if (url.startsWith('https:')) shell.openExternal(url);
        return { action: 'deny' }
    })

    return aboutWin;
}
function closeaboutWin() {
    if (aboutWin && !aboutWin?.isDestroyed()) {
        aboutWin?.close();
    }
    aboutWin = null;
}

function openaboutWin() {
    if (!aboutWin || aboutWin?.isDestroyed()) {
        aboutWin = createaboutWin();
    }
}
function showaboutWin() {
    aboutWin?.show();
}

function hideaboutWin() {
    aboutWin.hide();
}
// 写一个show和hide切换
function showHideaboutWin() {
    aboutWin.isVisible() ? aboutWin.hide() : aboutWin.show();
}
function goHomeaboutWin() {
    aboutWin.loadURL('http://localhost:3456/about')
}

function minimizeaboutWin() {
    aboutWin.minimize();
}

function focusaboutWin() {
    if (!aboutWin || aboutWin?.isDestroyed()) {
        aboutWin = createaboutWin();
    } else {
        // Focus on the main window if the user tried to open another
        if (aboutWin.isMinimized()) aboutWin.restore();
        if (!aboutWin.isVisible()) aboutWin.show();
        aboutWin.focus();
    }
}

function sendEuUpdateCanAvailable(arg, update) {
    if (aboutWin && !aboutWin?.isDestroyed()) {
        aboutWin.webContents.send('eu:update-can-available', {
            update: update,
            version: app.getVersion(),
            newVersion: arg?.version,
        });
    }
}

export {
    closeaboutWin,
    createaboutWin,
    showaboutWin,
    focusaboutWin,
    hideaboutWin,
    minimizeaboutWin,
    openaboutWin,
    sendEuUpdateCanAvailable,
    showHideaboutWin,
    goHomeaboutWin
};